// pages/personal/collect/collect.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    data: {},
    windowHeight: "",
    Page: 0,
    list: [],
    bookList: [],
    collectlist: {},
    movieslist: {},
    windowHeight: "",
    userInfo: app.globalData.userInfo
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '长按取消收藏',
      duration: 1000
    })
    //获取整个页面的高度
    wx.getSystemInfo({
      complete: (res) => {
        this.setData({
          windowHeight: res.windowHeight
        })
      },
    })
    this.getmovieidbyuserid();
  },
  // 通过userId获取收藏电影id
  async getmovieidbyuserid() {
    const db = wx.cloud.database()
    const collect = db.collection("collect")
    let that = this;
    await collect.where({
      "useropenid": wx.getStorageSync('openid')
    }).where({
      category: "collect"
    }).get({
      success: function (res) {
        let temparry = [];
        res.data.forEach(function (item, index) {
          temparry.push(item.movieid)
        })
        that.getmoviebyid(temparry)
      },
      fail: function (error) {
      }
    })
  },
  // 通过电影id获取电影信息
  async getmoviebyid(arry) {
    let that = this;
    const db = wx.cloud.database()

    const movies = db.collection("movies")
    const comm = db.command
    await movies.where({
      _id: comm.in(arry),
    }).get({
      success: function (res) {
        const reg = /[0-9\u4e00-\u9fa5]|\/|/g;
        res.data.forEach(item => {

          item.title = item.title.match(reg).join('').substring(0, 5) + "..."
          item.contries = item.contries.match(reg).join('').substring(0, 3)
          item.author = item.author.match(reg).join('').substring(0, 10) + "..."
        })
        that.setData({
          movieslist: res.data
        })

      },
      fail: function (error) {
        return error
      }
    })
  },
  // 取消收藏
  removecollect: async function (e) {
    let that = this;
    let tempmovieid = e.currentTarget.dataset.movieid;
    let tempuserid = wx.getStorageSync('openid');
    const db = wx.cloud.database();
    await db.collection("collect").where({
      "movieid": tempmovieid,
      "useropenid": tempuserid,
      "category": "collect"
    }).remove().then(res => {
      if (res.stats.removed == 1) {
        that.hideModal()
      }
      wx.showToast({
        title: '取消收藏成功！',
      })
      this.getmovieidbyuserid();

    })
  },
  // 显示
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target,
      movieid: e.currentTarget.dataset.movieid
    })
  },
  // 隐藏
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  //跳转详情
  todetail: function (options) {
    wx.navigateTo({
      url: '/pages/comm/detail/detail?id=' + options.currentTarget.dataset.id,
    })

  },

  // 触底加载
  loadmore: function () {
    wx.showToast({
      title: '正在拉取',
      icon: 'loading',
      duration: 1000
    })
  },
})